import 'package:flutter/material.dart';
import 'package:ibooks/utils/light_engine.dart';
import 'package:ibooks/widget/battery_widget.dart';
import 'package:ibooks/widget/text_indicator.dart';
import 'package:battery/battery.dart';

import '../model/index.dart';

class ReaderPage extends StatefulWidget {

  final Book book;

  ReaderPage({this.book});

  @override
  _ReaderPageState createState() => _ReaderPageState();
}

class _ReaderPageState extends State<ReaderPage> {

  LightEngine lightEngine;

  Battery _battery;

  bool isCharging = false;

  int _level = 0;

  @override
  void initState() {
    super.initState();
    lightEngine = new LightEngine(book: widget.book, stateSetter: setState);
    _battery = Battery();
    _battery.onBatteryStateChanged.listen((BatteryState event) {
      if (BatteryState.charging == event) {
        isCharging = true;
      }
    });
  }

  PageController pageController;

  Future<PageController> pageControllerFuture;

  static int currentLen = 0;

  static String chaptersName;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraint) {
          lightEngine.pageSize =
          new Size(constraint.maxWidth - 30, constraint.maxHeight - 70);
          if (null == pageControllerFuture) {
            pageControllerFuture = lightEngine.controller;
          }
          return Container(
            child: FutureBuilder(
                future: pageControllerFuture,
                builder: (BuildContext context, AsyncSnapshot<PageController> snapshot) {
                  if (ConnectionState.waiting == snapshot.connectionState) {
                    return new Center(
                      child: new TextIndicator(),
                    );
                  } else if (ConnectionState.done == snapshot.connectionState &&
                      !snapshot.hasError &&
                      snapshot.hasData &&
                      snapshot.data is PageController) {
                    pageController = snapshot.data;
//                    pageController.jumpToPage(widget.book.process);
                    print("page count ===> ${lightEngine.childCount}");
                    return PageView.custom(
                      childrenDelegate: new SliverChildBuilderDelegate(
                          _pageBuilder,
//                          childCount: totalPage,
                          addRepaintBoundaries: false,
                          addAutomaticKeepAlives: true
                      ),
                      controller: pageController,
                      onPageChanged: (currentPageNo) {
                        _battery.batteryLevel.then((int level) {
                          print("batteryLevel ===> $level");
                          _level = level;
                        });
                      },
                    );
                  } else {
                    return new Container(
                      padding: const EdgeInsets.all(20.0),
                      child: new Center(
                        child: new Text(
                          '解析失败：${snapshot.error}',
                        ),
                      ),
                    );
                  }
                }
            ),
          );
        }
      ),
    );
  }

  Widget _pageBuilder(BuildContext context, int index) {
    var content = lightEngine.getContent(index);
    print("content ===> $content}");
    var regExp = RegExp("第(.*?)章(.*?)\r");
//    regExp.
    Widget chapterChip;
    if (chaptersName != null) {
      chapterChip = Text(chaptersName);
    }
    var firstMatch = regExp.firstMatch(content);
    if (firstMatch != null) {
      chaptersName = "第${firstMatch.group(1)}章${firstMatch.group(2)}";
      chapterChip = Text(chaptersName);
    }

    currentLen = content.length;
    return Container(
      decoration: new BoxDecoration(
          color: Color.fromRGBO(135, 155, 65, 0.35)
      ),
      padding: const EdgeInsets.fromLTRB(15, 30, 15, 0),
      child: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              child: new Text(
                content.trim(),
                textScaleFactor: 1.2,
                maxLines: lightEngine.maxLines,
                style: TextStyle(
                  fontSize: 16,
                ),
              ),
            ),
          ),
          SizedBox(
            width: double.maxFinite,
            height: 30,
            child: Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(left: 10),
                  alignment: Alignment.centerLeft,
                  child: chapterChip??Text(""),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(right: 10),
                    alignment: Alignment.centerRight,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        BatteryWidget(isCharging: true,),
                        SizedBox(width: 10,),
                        Text((currentLen / lightEngine.totalLen).toStringAsFixed(2) + '%',
                          textAlign: TextAlign.right,
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

}
